package com.dmapp.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.example.com.skills_utf8.R;



class Image
{
	
	
	
	public String SaveToDisk( String url){
		
		String newImgPath ="";
		FileOutputStream fos;
		
		Bitmap bitmap = Utils1.returnBitMap(url);
		
		try {
			if (null != bitmap) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				Date dt = new Date();
				// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
				String picName = sdf.format(dt);
				// String picName = file.getName();
				newImgPath += File.separator + picName + ".jpg";
				fos = new FileOutputStream(newImgPath);
				int quality = 100;
				bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
				fos.flush();
				fos.close();
			} else {
				return null;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
			if (!bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}
		
		
		return newImgPath;
	}
	
	/**
	 * 为避免大图在上传和下载后显示，导致内存溢出，特对大图上传，采用压缩后在上传； 采用如下的图片压缩方案： 阈值： 尺寸: 长边1024;
	 * 体积：200KB
	 * 
	 * @param path
	 *            解码后的图片字符串
	 * @return
	 */
	public static String imageCompress(String imgPath) {
		if (null == imgPath || "".equals(imgPath)) {
			return "";
		}

		File file = new File(imgPath);
		String imgFileName = file.getName();
		String newImgPath = imgPath.substring(0, imgPath.indexOf(imgFileName));
		FileOutputStream fos = null;
		Bitmap bitmap = null;

		if (file.exists() && file.length() / 1024 > 200) {
			// 1 获取图片的原始大小
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgPath, options);
			if (options.mCancel || options.outWidth == -1
					|| options.outHeight == -1) {
				return "";
			}
			int originWidth = options.outWidth;
			int originHeight = options.outHeight;

			
			int size_x = 640; //..
			
			// 2. 按同比例压缩计算目标尺寸
			int dstWidth = originWidth;
			int dstHeight = originHeight;
			Log.i("TAG", "原始尺寸：" + dstWidth + "," + dstHeight);
			System.out.println("原始尺寸：" + dstWidth + "," + dstHeight);
			if (originWidth > size_x) {
				dstWidth = size_x;
				dstHeight = (int) ((float)size_x * originHeight / originWidth);

			}

			System.out.println("压缩尺寸：" + dstWidth + "," + dstHeight);
			// 3. 按照目标尺寸对图片进行解码，创建Bitmap
			options.inSampleSize = computeSampleSize(options, dstWidth,
					dstHeight);
			Log.i("TAG", "computeSampleSize(options, dstWidth,dstHeight)="
					+ computeSampleSize(options, dstWidth, dstHeight));
			System.out
					.println("computeSampleSize(options, dstWidth,dstHeight)="
							+ computeSampleSize(options, dstWidth, dstHeight));
			options.inJustDecodeBounds = false;
			options.inDither = false;
			Log.i("TAG", "inSampleSize：" + options.inSampleSize);
			Bitmap sourceBitmap = BitmapFactory.decodeFile(imgPath, options);
			options = null;
			if (null == sourceBitmap) {
				return null;
			}
			// 3.2 按照同比例缩放创建Bitmap
			bitmap = Bitmap.createScaledBitmap(sourceBitmap, dstWidth,
					dstHeight, false);

			// 4. 对Bitmap进行压缩处理，生成JPEG格式的图片
			try {
				if (null != bitmap) {
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					Date dt = new Date();
					// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
					String picName = sdf.format(dt);
					// String picName = file.getName();
					newImgPath += File.separator + picName + ".jpg";
					fos = new FileOutputStream(newImgPath);
					int quality = 100;
					bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
					fos.flush();
					fos.close();
				} else {
					return null;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// stony
				if (!sourceBitmap.isRecycled()) {
					sourceBitmap.recycle();
				}
				if (!bitmap.isRecycled()) {
					bitmap.recycle();
				}
			}
		} else {
			newImgPath = imgPath;
		}
		return newImgPath;
	}

	/**
	 * 计算缩放比
	 * 
	 * @param options
	 * @param target
	 * @return
	 */
	public static int computeSampleSize(BitmapFactory.Options options,
			int targetWidth, int targetHeight) {
		int w = options.outWidth;
		int h = options.outHeight;

		int candidateW = w / targetWidth;
		int candidateH = h / targetHeight;
		int candidate = Math.max(candidateW, candidateH);

		if (candidate == 0)
			return 1;
		return candidate;
	}

	/**
	 * 根据图片路径将图片Base64转换为字符串
	 * 
	 * @param path
	 * @return
	 */
	@SuppressLint("NewApi")
	public String bitmaptoString(String path) {
		// 将Bitmap转换成字符串
		String string = null;
		Bitmap bitmap = decodeFile(path);
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		bitmap.recycle();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		try {
			bStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return string;
	}

	/**
	 * y
	 * 
	 * @param f
	 * @return
	 */
	private Bitmap decodeFile(String f) {
		try {
			// decode image size
			File file = new File(f);
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(file), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 320;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 <= REQUIRED_SIZE
						|| height_tmp / 2 <= REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			o2.inPreferredConfig = Bitmap.Config.RGB_565;
			o2.inPurgeable = true;
			o2.inInputShareable = true;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}



	/**
	 * 将图片转化为字符串，
	 * 
	 */
	public String oom(String path) {
		return bitmaptoString(imageCompress(path));
	}

/*
 * 返回压缩后的路径.	
 */

	/*
	public String oom_file(String path){
		//return imageCompress(path);
		
		return "";
	}
*/
	
};


class Cfilter
{
	
};

public class Utils1 {

	
	final static String TAG ="Utils1";
	final static boolean DEBUG =true;
	final static boolean RELEASE =!DEBUG;
	
	/**
	 * 显示网络图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap returnBitMap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
			conn.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	/**
	 * 
	 */
	public static Bitmap returnBitMap(String url,  BitmapFactory.Options options) {
		URL myFileUrl = null; 
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} 
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is, null, options);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	

	/**
	 * 判断手机格式是否正确
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 判断email格式是否正确
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 判断是否全是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 保存用户账号
	 * 
	 * @param activity
	 * @param userName
	 *            用户账号
	 * @param password
	 *            用户密码
	 */

	public static void saveUserInfo(Activity activity, String userName,
			String password, boolean isRemember) {
		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("isRemember", isRemember);
		if (isRemember) {
			editor.putString("userName", userName);
			editor.putString("password", password);
		} else {
			editor.putString("userName", "");
			editor.putString("password", "");
		}
		editor.commit();
	}

	/**
	 * 隐藏键盘
	 * @param activity
	 */
	public static void hideKeybord(Activity activity) {	
		try{
			((InputMethodManager)activity.getSystemService(activity.INPUT_METHOD_SERVICE)).
			hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
		}catch(Exception e){
			
		}
	}
	
	public static  boolean networkIsAvailable( Context context) {
		NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		return (null != info && info.isAvailable());
	}
	
	
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;
	
	/**
	 * 检测网络是否可用
	 * @return
	 */
	public static boolean isNetworkConnected( Context context ) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}

	/**
	 * 获取当前网络类型
	 * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
	 */
	public static int getNetworkType( Context context ) {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}		
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			extraInfo =extraInfo.trim();
			if(extraInfo.length() != 0){
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}
	
	
	
	
	
//////////////////////////////////////////////////////////////////////////
	
	
    /**把数据源HashMap转换成json 
     * @param map  
     */  
    public static String hashMapToJson(HashMap map) {  
        String string = "{";  
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {  
            Entry e = (Entry) it.next();  
            string += "'" + e.getKey() + "':";  
            string += "'" + e.getValue() + "',";  
        }  
        string = string.substring(0, string.lastIndexOf(","));  
        string += "}";  
        return string;  
    }  
	
	
	/**
	 * 将整形转换成2100-10-10形式
	 * @param token
	 * @return
	 */
	public static String getTime(String token){
		 token +="000";
		long time_long =Long.parseLong(token);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date(time_long));
	}
	
	
	/*
	 * 给出提示
	 */
	public static void NoticeNew(Activity activity, int length){
		
		
		if(g.RELEASE)
			return;
		
		
		if (length > 0) {

			String str = String.valueOf(length);
			Toast.makeText(activity, "已增加更新: " + str,
					Toast.LENGTH_SHORT).show();

		} else {

			Toast.makeText(activity, "无新的内容~", Toast.LENGTH_SHORT)
					.show();

		}
		
		
	}
	
	
	
	
	public static void showToastShort(Context context, String messsage) {
		Toast.makeText(context, messsage, Toast.LENGTH_SHORT).show();
	}
	
	public static void showToastLong(Context context, String messsage) {
		Toast.makeText(context, messsage, Toast.LENGTH_LONG).show();
	}

	
	public static void MessageBox(Activity activity, String text) {
		new AlertDialog.Builder(activity).setTitle("温馨提示").setMessage(text)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						dialog.dismiss();

					}
				})
//				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						// TODO Auto-generated method stub
//
//					}
//				})
				.create().show();

	}	
	

	
	/**
	 * 将图片转化为字符串，
	 * 
	 */
	public static String ImageToBase64(String path) {
		
		if(mImage == null)
			mImage = new Image();
		
		return mImage.oom(path);
	} private static Image mImage ;

	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	

	private static ProgressDialog progress = null;
	
	/**
	 * 显示加载对话框
	 * 
	 * @param messsage
	 *            内容
	 */
	static public void showLoadingDialog(Activity activity, String messsage) {
		
		if ((progress != null) &&progress.isShowing()) {
			return;
		}
		progress = new ProgressDialog(activity);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage(messsage);
		progress.show();

	} 
	
	/**
	 * 隐藏加载对话框
	 */
	static public void dismissLoadingDialog() {
		if (progress != null) {
			progress.dismiss();
		}
	}
	
	
	
	
	
	static public void phone_call(Activity activity, String num){
		
		Intent i = new Intent("android.intent.action.CALL", Uri
				.parse("tel:" + num));
		activity.startActivity(i);
	
	}
	

	
	/*
	static public void showNotification(Activity activity,long cancelTime, String text) {
		try {
			Context app = activity.getApplicationContext();
			NotificationManager nm = (NotificationManager) app
					.getSystemService(Context.NOTIFICATION_SERVICE);
			final int id = Integer.MAX_VALUE / 13 + 1;
			nm.cancel(id);

			long when = System.currentTimeMillis();
			Notification notification = new Notification(notifyIcon, text, when);
			PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(), 0);
			notification.setLatestEventInfo(app, notifyTitle, text, pi);
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			nm.notify(id, notification);

			if (cancelTime > 0) {
				
				
				Message msg = new Message();
				msg.what = MSG_CANCEL_NOTIFY;
				msg.obj = nm;
				msg.arg1 = id;
				UIHandler.sendMessageDelayed(msg, cancelTime, this);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	*/

	
	public static String UrlImageToFile(String url) {
		
		if(mImage == null)
			mImage = new Image();
		
		return mImage.SaveToDisk(url);
	}
	
	
	/**
	 * 判断密码是否有效
	 * @param context
	 * @param password
	 * @return
	 */
	public static boolean vaildPassword(Context context, String password){  //
		
		boolean b = true;
/*		
		if( password.length() > 32){  // 限制长度
			Utils1.showToastShort(context, "密码过长~");
			b = false;
		}
*/		
		// 对java的正则无力...       判断是否有空格,  判断是否空字符串
		if(password == null || password.length() == 0)
			b =false;
		
		if(password.length() < 6 || password.length() > 32)
			b = false;
		
		
		// java的正则糟糕透了.
		Pattern p = Pattern
				.compile("[0-9a-zA-Z]*");  //非[6,32]..     http://www.java3z.com/cwbwebhome/article/article8/Regex/Java.Regex.Tutorial.html
		Matcher m = p.matcher(password);  // 
		if(!m.matches())
			b = false;
		
		if(b== false){
	//		Utils1.showToastShort(context, "无效密码~");  // "请输入有效密码~"
			System.out.println("无效密码: "+password);
		}
		
		return b;
		
		
	}
	
	/**
	 * 简化代码而已
	 */
	public static void json_erro( Context context, JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		System.out.println("JSONException" + e.toString());
		Toast.makeText(context, "数据解析错误", Toast.LENGTH_SHORT).show();
	}
	
	
	/**
	 * 用户未登录时，提示用户登录
	 */
	public void showLoginDialog(final Activity activity, final Class<?> cls) {
		
		AlertDialog dialog = new AlertDialog.Builder(activity)
				.setTitle("提示")
				.setMessage("您还没有登录，请先登录")
				.setPositiveButton("登录", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(activity,
								cls);
						activity.startActivity(intent);
						activity.overridePendingTransition(R.anim.in_from_right,
								R.anim.out_to_left);
						dialog.dismiss();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();

		dialog.show();
	}
	
	
	public static boolean isEnglishWord(String str){		//digirun
		Pattern pattern = Pattern.compile("[a-z]+|[A-Z]+");
		Matcher is = pattern.matcher(str);
		if (!is.matches()) {
			return false;
		}
		
		return true;
	} 
	
	public static boolean isEnglish(CharSequence s){
		
		boolean b = true;
		
	
		Pattern p = Pattern
				.compile("[a-zA-Z]*");  //非[6,32]..   s="abc" [a-zA-Z] 为啥mathces()不上.. 不应该是匹配上a,b,c吗;
		Matcher m = p.matcher(s);  // 
		if(!m.matches())
			b = false;
		
		if(b== false){
		}
		
		return b;
		
	}
	
	
	
	public static boolean isEmpty(String s){
		if(s.trim().length() == 0)
			return true;
		else
			return false; 
	}
	

	
	/*
	
	class cClampLength
	{
		int change_length =0;
		int length =10;
		
		public cClampLength() {
			// TODO Auto-generated constructor stub
		}
		
	};

	
	private static cClampLength clamp;
	public static boolean clamp_length(String s){
		
		if(clamp == null)
			return new cClampLength();
		else
			return clamp;
	}
	
	*/


	
	/**
	 * @Description: TODO(判断sdcard是否可用)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return 
	 */
	public static boolean isSDCardAvailable() {
		if (Environment.getExternalStorageState().equals("mounted")) {
			return true;
		}
		return false;
	}

	/**
	 * @Description: TODO(判断网络是否可用)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return 
	 */
	public static boolean isNetworkAvailable(Context appContext) {
		Context context = appContext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService("connectivity");
		if (connectivity == null) {
			return false;
		}
		NetworkInfo[] info = connectivity.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].isConnected()) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * @Description: TODO(获取当前时间)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return 
	 */
	public static String getNowTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		return format.format(Calendar.getInstance().getTime());
	}
	
	public static String getNowTime1() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(Calendar.getInstance().getTime());
	}
	

	/**
	 * @Description: TODO(获取屏幕尺寸)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return 
	 */
	public static int[] getScreenSize(Activity context) {
		int[] data = new int[2];
		DisplayMetrics mDisplayMetrics = new DisplayMetrics();
		context.getWindowManager().getDefaultDisplay()
				.getMetrics(mDisplayMetrics);
		data[0] = mDisplayMetrics.widthPixels;
		data[1] = mDisplayMetrics.heightPixels;

		return data;
	}
	
	
	
	public static int getStatusHeight(Activity activity) {  //可以使用Build判断版本;
		
		
		// 不支持某些版本.. android2.3.5
		int StatusHeight = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
		
		if(StatusHeight == 0)
		{
			// 38像素      http://www.2cto.com/kf/201205/130561.html
			Class<?> c = null;
			Object obj = null;
			java.lang.reflect.Field field = null;
			int x = 0, sbar = 0;
			try {
			    c = Class.forName("com.android.internal.R$dimen");
			    obj = c.newInstance();
			    field = c.getField("status_bar_height");
			    x = Integer.parseInt(field.get(obj).toString());
			    sbar = activity.getResources().getDimensionPixelSize(x);
			} catch (Exception e1) {
				Log.e("", "get status bar height fail");
			    e1.printStackTrace();
			} 
			
			StatusHeight =sbar;
		}
		
		
		return StatusHeight;
		
	}
	
	

	
	public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    // 宽和高都大于实际需要
    if (height > reqHeight || width > reqWidth) {
	        if (width > height) { //比较图片长宽,用最大的算比例...(int)Math.floor(a + 0.5f);  floor:函数返回不大于参数的最大整数
	            inSampleSize = Math.round((float)height / (float)reqHeight);
	        } else {
	            inSampleSize = Math.round((float)width / (float)reqWidth);
	        }
	    }
	    return inSampleSize;
	}
	
	
	
	public static Bitmap decodeFile(String path, int REQUIRED_SIZE_x, int REQUIRED_SIZE_y) {
		try {
			// decode image size
			File file = new File(path);
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(file), null, o);

			// Find the correct scale value. It should be the power of 2.
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 <= REQUIRED_SIZE_x
						|| height_tmp / 2 <= REQUIRED_SIZE_y)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			o2.inPreferredConfig = Bitmap.Config.RGB_565;
			o2.inPurgeable = true;
			o2.inInputShareable = true;
			return BitmapFactory.decodeStream(new FileInputStream(path), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}
	

	
	
	
	// http://blog.csdn.net/sevensundark/article/details/7616450
	public static int px2dip(Context context, float pxValue){
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int)(pxValue / scale + 0.5f);
	}

	public static int dip2px(Context context, float dipValue){
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int)(dipValue * scale + 0.5f);
	}
	
	
	
	
	public static boolean isAppOnForeground(Context context) {
        // Returns a list of application processes that are running on the
        // device
         
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<RunningAppProcessInfo> appProcesses = activityManager
                        .getRunningAppProcesses();
        if (appProcesses == null)
                return false;

        for (RunningAppProcessInfo appProcess : appProcesses) {
                // The name of the process that this object is associated with.
                if (appProcess.processName.equals(packageName)
                                && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                }
        }

        return false;
	}
	
	public static boolean isAppOnForeground(Context context, String packageName) {
        // Returns a list of application processes that are running on the
        // device
         
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        

        List<RunningAppProcessInfo> appProcesses = activityManager
                        .getRunningAppProcesses();
        if (appProcesses == null)
                return false;
        
        for (RunningAppProcessInfo appProcess : appProcesses) {
                // The name of the process that this object is associated with.
                if (appProcess.processName.equals(packageName)
                                && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                }
        }
        
     

        return false;
	}
	
	
	
	public static boolean isAppOnBackground(Context context, String packageName) {
        // Returns a list of application processes that are running on the
        // device
         
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        

        List<RunningAppProcessInfo> appProcesses = activityManager
                        .getRunningAppProcesses();
        if (appProcesses == null)
                return false;
        
        for (RunningAppProcessInfo appProcess : appProcesses) {
                // The name of the process that this object is associated with.
                if (appProcess.processName.equals(packageName)
                                && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                        return true;
                }
        }
        
     

        return false;
	}
	
	

	static public void WaitMs(int delay)
	{
	    try {
	        Thread.sleep(delay);
	    } catch (InterruptedException e) {}
	
	}
	
	
	// error
	public static boolean isContainNum(String str) {
		Pattern pattern = Pattern.compile("[0-9]+"); 
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}
	
	
	public static void do_hardwork(){
		try {
			Socket s = new Socket("11.11.11.11",11);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
	}
	
	//20140221
	
	public static double byte2KB(long bytes){
		return (double)bytes / (1024);
	}
	
	public static double byte2MB(long bytes){
		return (double)bytes / (1024*1024);
	}
	
	
	
}














